using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;

namespace OpenComposite.EII.Designer.Workflow
{
	public class TypeDescriptorContext : ITypeDescriptorContext
	{
		public TypeDescriptorContext(IContainer container, object instance,
			PropertyDescriptor propDescriptor, IServiceProvider serviceProvider)
		{
			_container = container;
			_instance = instance;
			_propDescriptor = propDescriptor;
			_serviceProvider = serviceProvider;
			if ( propDescriptor != null && instance != null && propDescriptor.ComponentType == instance.GetType() )
				_oldValue = propDescriptor.GetValue(instance);
		}

		private IContainer _container;
		private object _instance;
		private object _oldValue;
		private PropertyDescriptor _propDescriptor;
		private IServiceProvider _serviceProvider;

		#region ITypeDescriptorContext Members

		public IContainer Container
		{
			get { return _container; }
		}

		public object Instance
		{
			get { return _instance; }
		}

		public void OnComponentChanged()
		{
			System.ComponentModel.Design.IComponentChangeService changeSvc =
				(System.ComponentModel.Design.IComponentChangeService)
				_serviceProvider.GetService(typeof(System.ComponentModel.Design.IComponentChangeService));
			if ( changeSvc != null ) {
				changeSvc.OnComponentChanged(this.Instance, this.PropertyDescriptor,
											 _oldValue, this.PropertyDescriptor.GetValue(this.Instance)); 
			}
		}

		public bool OnComponentChanging()
		{
			System.ComponentModel.Design.IComponentChangeService changeSvc =
				(System.ComponentModel.Design.IComponentChangeService)
				_serviceProvider.GetService(typeof(System.ComponentModel.Design.IComponentChangeService));
			if ( changeSvc != null ) {
				changeSvc.OnComponentChanging(this.Instance, this.PropertyDescriptor);
				return true;
			} else {
				return true;
			}
		}

		public PropertyDescriptor PropertyDescriptor
		{
			get { return _propDescriptor; }
		}

		#endregion

		#region IServiceProvider Members

		public object GetService(Type serviceType)
		{
			if ( _serviceProvider != null ) {
				return _serviceProvider.GetService(serviceType);
			} else {
				return null;
			}
		}

		#endregion
	}
}
